import axios from 'axios'
import store from '@/store'
import { message } from 'antd'
import { customHistory } from '@/utils/history'
import { logout } from '@/store/actions/login'

const http = axios.create({
  baseURL: process.env.REACT_APP_URL,
  timeout: 5000,
})

http.interceptors.request.use((config) => {
  if (config.url !== '/sys/login') {
    config.headers.Authorization = `Bearer ${store.getState().login}`
  }
  return config
})

http.interceptors.response.use(
  (res) => {
    if (!res.data.success) {
      message.info(res.data.message)
      console.log('失败', res)
      return Promise.reject(res)
    } else {
      return res
    }
  },
  (error) => {
    if (!error.response) {
      message.info('网络超时，请稍后再试')
      return Promise.reject(error)
    }
    if (error.response.data.code === 10002) {
      customHistory.push('/login')
      store.dispatch(logout())
    }
    return Promise.reject(error)
  }
)

export default http
